<template>
	<view style="margin: 10px;background-color: #fff;border-radius: 10px;">		
	<!-- <view class="uni-reture">
		<uni-icons type="back" size="26" @click="goBack"></uni-icons>
	</view> -->
		<!-- <image class="logo" src="/static/logo.png"></image> -->
	    <view style="padding: 15px;padding-right: 15px;">
			<uni-forms ref="baseForm" :rules="rules" :modelValue="FormData">
				<uni-forms-item label="整改人:">
					<uni-easyinput v-model="userName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="整改车间:">
					<uni-data-select
						v-if="editAble"
						v-model="FormData.workshopId"
						:localdata="shopOption"
						@change="selectChange"
						:clear="false"
					></uni-data-select>
					<uni-easyinput v-if="!editAble" v-model="FormData.workshop" disabled="true"/>
					<!-- <uni-easyinput v-model="FormData.workshopId" disabled="true"/> -->
				</uni-forms-item>
				<uni-forms-item label="整改条线:" v-if="FormData.lineId !=null">
					<uni-easyinput v-model="FormData.lineName" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="区域:">
					<uni-data-select
						v-if="editAble"
					    v-model="FormData.workshopareaId"
					    :localdata="spaceOption"
					    @change="selectChange"
						:clear="false"
					></uni-data-select>
					<uni-easyinput v-if="!editAble" v-model="FormData.workshoparea" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="6源问题:" v-if="FormData.sixProblem !=''">
					<uni-easyinput v-model="FormData.sixProblem" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="整改时间:" required name="abarbeitungTime">
					<uni-datetime-picker type="datetime" :clear-icon="false" v-model="FormData.abarbeitungTime" @maskClick="maskClick" />
				</uni-forms-item>
				<uni-forms-item label="问题描述:">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.description" disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="备注:" v-if="!sixSource">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.note" placeholder="请输入备注"/>
				</uni-forms-item>
				<uni-forms-item label="整改措施:" required name="note" v-if="sixSource">
					<uni-easyinput type="textarea" autoHeight v-model="FormData.note" placeholder="请填写6源问题整改措施"/>
				</uni-forms-item>
				<uni-forms-item label="改前图片:">
					<image 
					class="uni-imge" 
					v-for="(item, index) in FormData.frontImageListData"
					:key="index" 
					@click="previewImage(item.url)" 
					:src='item.url'></image>
				</uni-forms-item>
				<uni-forms-item label="改后图片:" required name="backImageListData">
					<uni-file-picker class="form-up-file" fileMediatype="image" :image-styles="imageStyles" limit="9" @select='onFileChange' @delete='imgDelet'></uni-file-picker>
				</uni-forms-item>
			</uni-forms>
			<view class="demo-uni-but">
				<button style="margin-top: 10px; background-color: #007aff" type="primary"  @click="clickInter('baseForm')">提交</button>
				<button style="margin-top: 10px;" type="default" @click="toUnpri">无法处理</button>
				<button style="margin-top: 10px;" type="warn" @click="queryLine">转交</button>
				<!-- <uni-row :gutter="gutter">
					<uni-col :span="8" style="text-align: center;">
				<button class="mini-btn" type="primary" size="mini" @click="clickInter('baseForm')">提交</button>
					</uni-col>
					<uni-col :span="8" style="text-align: center;">
				<button class="mini-btn-uni" type="default" size="mini" @click="toUnpri">无法处理</button>
					</uni-col>
					<uni-col :span="8" style="text-align: center;">
				<button class="mini-btn-uni" type="warn" size="mini" @click="changeArea">转交</button>
					</uni-col>
				</uni-row> -->
			</view>
		<view>
			<!-- 提示窗示例 -->
			<uni-popup ref="alertDialog" type="dialog" :mask-background-color="maskColor">
				<uni-popup-dialog type="warn" cancelText="取消" confirmText="确定" title="请选择转交区域" @confirm="dialogConfirm"
					@close="dialogClose">
					<view style="width: 100%;">
						<view style="margin-bottom: 5px;">
						<uni-data-select
							v-if="isShowLine"
							class="dialog-select"
						    v-model="lineId"
						    :localdata="lineOption"
							:clear="false"
							label="选择"
							@change="lineChange"
							placeholder="请选择转交条线"
						></uni-data-select>
						</view>
						<uni-data-select
							class="dialog-select"
						    v-model="areaId"
						    :localdata="spaceOption"
							:clear="false"
							label="选择"
							placeholder="请选择转交区域"
						></uni-data-select>
					</view>
					<!-- <uni-forms>
						<uni-forms-item label="转交区域:" name="workshopareaId">
							
						</uni-forms-item>
					</uni-forms> -->
					</uni-popup-dialog>
			</uni-popup>
		</view>
		</view>
		</view>
	</view>
</template>

<script>
	import { post, fileUpLoad, postForm } from '../../../utils/request.js';
	export default {
		data() {
			return {
				lineId: '',
				lineOption: [],
				isShowLine: false,
				maskColor: 'rgba(0, 0, 0, 0.4)',
				areaId: '',
				// 校验规则
				rules: {
					backImageListData: {
						rules: [{
							required: true,
							errorMessage: '请上传图片'
						}]
					},
					abarbeitungTime: {
						rules: [{
							required: true,
							errorMessage: '请选择整改时间'
						}]
					},
					note: {
						rules: [{
							required: true,
							errorMessage: '请输入6源问题整改措施'
						}]
					},
					},
				sixSource: false,
				note: '',
				editAble: false,
				spaceOption: [],
				imageStyles:{
					width:70,
					height:70,
					border:{
						color:"rgb(238, 238, 238)",
						width:2,
						style:'dashed',
						radius:'2px'
					}
				},
				title: '',
				id: '',
				userInfor: uni.getStorageSync('userInfor'),
				userName: '',
				gutter: 2,
				FormData: {
					name: '',
					code: '',
					abarbeitungTime: Date.now()
				},
				checkUserId: '',
				userInfor: uni.getStorageSync('userInfor'),
				workshopName: '',
				workshopareaName: '',
				checkName:'检&ensp;车&ensp;人：',
				single:  Date.now(),
				mediaType:['image', 'audio']
			}
		},
		onShow() {
			//debugger
			/* let note = uni.getStorageSync('note')
			if(note != '') {
				this.FormData.note = note
			} */
		},
		onLoad(options) {
			this.id = options.id
			this.userInfor = uni.getStorageSync('userInfor')
			this.userName = this.userInfor.name
			this.workshopName = this.userInfor.workshop
			this.workshopareaId = this.userInfor.workshopareaId
			this.checkUserId = this.userInfor.userId
			this.getData()
		},
		methods: {
			clickInter(ref){
				this.$refs[ref].validate().then(res => {
					let saveData = {}
					saveData = {
						abarbeitungTime: this.FormData.abarbeitungTime,
						abarbeitungUserId: this.checkUserId,
						backImage: '',
						backImageListData: this.FormData.backImageListData,
						note: this.FormData.note,
						id: this.id
					}
					post('/problem/submit/wait', saveData)
					      .then(data => {
							  if(data.code == 200) {
								  uni.showToast({
								  	title: '数据保存成功！',
								  	duration: 1000
								  });
								uni.removeStorageSync('note');
								uni.switchTab({
					                url: '/pages/work/index'
					            });
							  } else {
								  uni.showToast({
								    icon: 'none',
								    title: data.message
								  });
							  }
					      })
					      .catch(err => {
					        uni.showToast({
					          icon: 'none',
					          title: '保存失败，请检查接口返回'
					        });
					      });
				}).catch(err => {
					console.log('err', err);
				})
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				postForm('/problem/selectById', {id: this.id} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							this.FormData = data.data
							this.FormData.abarbeitungTime = Date.now()
							if(this.FormData.frontImageListData != '' && this.FormData.frontImageListData !=null) {
								uni.hideLoading();
							} else {
								uni.hideLoading();
							}
							if(this.FormData.sixProblem === '') {
								this.rules.note.rules[0].required = false
								this.sixSource = false
							} else {
								this.rules.note.rules[0].required = true
								this.sixSource = true
							}
							//this.getUser()
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			getUser() {
				postForm('/user/selectById', {id: this.userInfor.userId} )
				    .then(data => {
						if(data.code == 200) {
							this.FormData.checkUserId = data.data.name
							this.FormData.workshopId = data.data.workshop
							this.FormData.workshopareaId = data.data.workshoparea
							this.workshopareaName = data.data.workshoparea
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			toUnpri() {
				let urlId = this.id
				uni.navigateTo({
				    url: '/pages/position/handel/unPri?id=' + urlId // 跳转页面的路径
				});
			},
			goBack() {
				uni.switchTab({
					url: '/pages/position/handel/index' // 跳转页面的路径
				});
			},	
			queryLine() {
				postForm('/lineAreaBase/getShowLineByWorkshop', {workShopId: this.FormData.workshopId} )
				    .then(data => {
						if(data.code == 200) {
							let resData = data.data
							if(resData.isShowLine) {
								this.isShowLine = resData.isShowLine
								let midData = resData.lineBaseList
								let linData = []
								for(var i = 0; i < midData.length; i++) {
									linData[i] = {}
									linData[i].value = midData[i].id
									linData[i].text = midData[i].lineName
								}
								this.lineOption = linData
							} else {
								this.changeArea()
								this.isShowLine = resData.isShowLine
							}
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
				this.$refs.alertDialog.open()
			},
			
			lineChange(e) {
				postForm('/lineAreaBase/getAreasByLine', {lineId: e} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							this.spaceOption = []
							this.FormData.workshopareaId = ''
							if(data.data) {
							let area = data.data
							let areaData = []
							for(var i = 0; i < area.length; i++) {
								areaData[i] = {}
								areaData[i].value = area[i].id
								areaData[i].text = area[i].areaName
							}
							this.spaceOption = areaData
							}
							//console.log(this.FormData)
							//debugger
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
			},
			changeArea() {
				//this.FormData.workshopId
				postForm('/workshop-area-base/findById', {workShopId: this.FormData.workshopId} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							if(data.data.areas) {
							let area = data.data.areas
							let areaData = []
							for(var i = 0; i < area.length; i++) {
								areaData[i] = {}
								areaData[i].value = area[i].id
								areaData[i].text = area[i].areaName
							}
							this.spaceOption = areaData
							}
							//console.log(this.FormData)
							//debugger
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
				this.$refs.alertDialog.open()
			},
			
			dialogConfirm() {
				if(this.isShowLine) {
					this.editSaveLine()
				} else {
					this.editSaveArea()
				}
			},
			editSaveArea() {
				postForm('/problem/updateAreaIdById', {id: this.id, areaId: this.areaId} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							uni.showToast({
								title: '修改成功！',
								duration: 2000
							});
							uni.switchTab({
							    url: '/pages/work/index'
							});
							//this.getUser()
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
				console.log('点击确认')
			},
			editSaveLine() {
				postForm('/problem/updateLineAreaIdById', {id: this.id, areaId: this.areaId,lineId: this.lineId} )
				    .then(data => {
						if(data.code == 200) {
							//debugger
							uni.showToast({
								title: '修改成功！',
								duration: 2000
							});
							uni.switchTab({
							    url: '/pages/work/index'
							});
							//this.getUser()
						} else {
							  uni.showToast({
							    icon: 'none',
							    title: data.message
							  });
						}
				    })
				    .catch(err => {
				        uni.showToast({
				           icon: 'none',
				          title: '获取数据失败，请检查接口返回'
				        });
				    });
				console.log('点击确认')
			},
			dialogClose() {
				console.log('点击关闭')
			},
			previewImage(url) {
				let img = []
				img[0] = url
				uni.previewImage({
					current: 0,
				    urls: img // 图片列表
				    });
			},
			//文件上传
			async onFileChange(event) {
				try {
				    const files = event.tempFiles;
				    if (!files || files.length === 0) {
				      uni.showToast({ title: '请选择文件', icon: 'none', duration: 2000 });
				      return;
				    }
				
				    uni.showLoading({ title: '上传中...', mask: true });
				
				    // 循环上传，避免并发问题
				    for (const file of files) {
				      try {
				        let response = await fileUpLoad('/alone/uploadImages', file.path);
				        if (response) {
				          this.FormData.backImageListData.push({ url: response });
				        }
				      } catch (error) {
				        console.error('单文件上传失败:', error);
				        // 可以继续上传其他文件，或 break 终止
				      }
				    }
				
				    uni.hideLoading();
				    uni.showToast({ title: '上传完成，等待提交！', icon: 'success', duration: 2000 });
				  } catch (error) {
				    uni.hideLoading();
				    uni.showToast({ title: '上传失败，请重试', icon: 'none', duration: 2000 });
				    console.error('文件上传错误:', error);
				  }
			},
			
			//图片删除
			imgDelet(e) {
				let index = e.index
				this.FormData.backImageListData.splice(index, 1);
			},
		    change(e) {
				this.single = e
				console.log('change事件:', this.single = e);
						},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			maskClick(e){
				console.log('maskClick事件:', e);
			}
		}
	}
</script>

<style>
	/* .uni-button-color {
		margin-top: 20px;
		background-color: #007aff !important;
	} */
	.uni-text {
		font-weight: 500;
		font-size: 14px;
		margin-bottom: 10px;
	}
.is-disabled {
	    color: #000 !important;
	}
	.uni-stat__select {
	    display: flex;
	    align-items: center;
	    width: 100%;
	    flex: 1;
		height: 35px;
	    box-sizing: border-box;
		border: 1px solid #e5e5e5;
	}
	/* uni-form  lable样式 */
	.uni-forms-item__label {
		font-weight: 600 !important;
		width: 80px !important;
	  text-align: right !important;
	  justify-content: flex-end !important;
	}
	.uni-imge {
		height: 70px;
		width: 70px;
	}
	.demo-uni-row {
		padding-top: 10px;
	}
	.demo-uni-but {
		padding-top: 10px;
		text-align: center;
	}
	.demo-uni-col {
		margin-left: 10px;
	}
	.mini-btn{
		background-color: #007aff !important;
		display: inline;
	}
	.mini-btn-uni {
		padding-left: 10px !important;
		padding-right: 10px !important;
	}
	.form-up-file {
		margin-left: 10px;
	}
	/* 全局样式或当前页面的样式 */
	.uni-popup__mask {
	  background-color: rgba(0, 0, 0, 0.4) !important; /* 强制覆盖 */
	}
	/* 确保弹框居中 */
.uni-popup-dialog {
	box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 3px 1px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
